package main

import (
	"fmt"
	"log"
	"os"

	"github.com/skip2/go-qrcode"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/canvas"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/dialog"
	"fyne.io/fyne/v2/layout"
	"fyne.io/fyne/v2/widget"
)

// 生成二维码
func (app *config) generateQRcode() func() {
	return func() {

		w := fyne.CurrentApp().NewWindow("生成二维码")

		input := widget.NewEntry()
		input.SetPlaceHolder("请输入字符串")
		input.Wrapping = 2     // 开启自动换行
		input.MultiLine = true //多行输入

		image := canvas.NewImageFromFile("./image/code.png")
		image.Resize(fyne.NewSize(30, 30))
		image.FillMode = canvas.ImageFillOriginal

		generateQRcodeBtn := widget.NewButton("生成二维码", func() {})

		emptyBtn := widget.NewButton("清空", func() {
			input.SetText("")
		})

		saveBtn := widget.NewButton("保存", app.saveImg(w))

		funcLayout := container.New(layout.NewHBoxLayout(), generateQRcodeBtn, emptyBtn, saveBtn)
		inputLayout := container.New(layout.NewVBoxLayout(), input, image, funcLayout)
		generateQRcodeBtn.OnTapped = func() {
			if input.Text == "" {
			    return
			}
			err := qrcode.WriteFile(input.Text, qrcode.Medium, 256, "./generateQRcode/qr.png")
			if err != nil {
				fmt.Println("生成二维码时出错：", err)
				os.Exit(1)
			}
			log.Println("QR code generated and saved as qrcode.png")

			// 创建一个新的 Image 对象，使用新的路径
			newImage := canvas.NewImageFromFile("./generateQRcode/qr.png")
			newImage.Resize(fyne.NewSize(30, 30))
			newImage.FillMode = canvas.ImageFillOriginal
			// 将新的 Image 对象替换旧的对象
			inputLayout.Objects[1] = newImage
		}
		allLayout := container.NewBorder(inputLayout, nil, nil, nil, nil)
		w.SetContent(allLayout)

		w.SetFixedSize(true) // 设置固定大小，避免用户拖动改变大小

		// start 监听主窗口的关闭事件
		// 前提是必须设置主窗口
		w.SetOnClosed(func() {
			w.Close()
		})
		// end 监听主窗口的关闭事件

		// 设置窗口大小,
		w.Resize(fyne.NewSize(450, 260))
		w.CenterOnScreen()
		w.Show()
	}
}

// 保存图片
func (app *config) saveImg(win fyne.Window) func() {
	return func() {
		// 显示文件保存对话框
		dialog.ShowFileSave(func(writer fyne.URIWriteCloser, err error) {
			if err != nil {
				dialog.ShowError(err, win)
				return
			}

			/* // 将图片写入文件
			if err := png.Encode(writer, "./generateQRcode/qr.png"); err != nil {
				dialog.ShowError(err, win)
				return
			} */

		}, win)
	}
}
